/**
 * Created by haoxuanli on 16/5/13.
 */
'use strict';
var router     = require('express').Router();
var superagent = require('superagent');
var http = require('http');
var querystring = require('querystring');
const url = require("url");

exports.request = function (params, callback){
    var cururl = url.parse(params.api);
    var postData = querystring.stringify(params);
    var options = {
        hostname:cururl.hostname,
        port:cururl.port,
        path:cururl.path,
        method:params.type,
        headers:{
            'Accept':'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding':'gzip, deflate',
            'Accept-Language':'zh-CN,zh;q=0.8',
            'Connection':'keep-alive',
            'Content-Length':postData.length,
            'token':params.token||"",
            'Content-Type':'application/x-www-form-urlencoded;',
            // 'Cookie':'imooc_uuid=fe4eb00a-b08b-4442-a87d-c077f0fa94dc; imooc_isnew_ct=1482112514; loginstate=1; apsid=I3ODRkMzRiY2MzNjZkZDlkNzZkZDk3OGYwNGFkYTEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMTAyNjA1OAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxMjE0NDgzNjM5QHFxLmNvbQAAAAAAAAAAAAAAAAAAADhjOTM3MTEyMTVkZDJkODBiZGQ5MGZhYjUxZDk2YTNkADZbWAA2W1g%3DYj; last_login_username=1214483639%40qq.com; PHPSESSID=dlq6ctudtje87erfq523b0dak7; jwplayer.volume=71; IMCDNS=0; Hm_lvt_f0cfcccd7b1393990c78efdeebff3968=1482112514,1482372528,1482377953,1482457056; Hm_lpvt_f0cfcccd7b1393990c78efdeebff3968=1482460689; imooc_isnew=2; cvde=585c7fe052b01-26',
            'Host':'',
            'Origin':'',
            'Referer':'',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36',
            'X-Requested-With':'XMLHttpRequest'
        }
    }

    var req = http.request(options,function(res){
        var buffers = [];
        res.setEncoding('utf8');
        res.on('data',function(chunk){
            buffers.push(chunk);
        })
        res.on('end',function(){
           return callback(null,buffers);
        })
    })

    req.on('error',function(e){
           return callback(e,null);
    })

    req.write(postData)
    req.end();
}

exports.reqs = function(params , callback){
      superagent
      .post(params.api)
      .send(params) // sends a JSON post body
      .set('Content-Type', 'application/x-www-form-urlencoded;')
      .set('token', params.token||"")
      .end((err, res) => {
        if(err){
            return callback(err,null)
        }else{
            return callback(null,res.text)
        }   
      });
}